import React from 'react'
import PropTypes from 'prop-types'
import {AgGridReact} from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';
import HeaderBar from "../header/HeaderBar";
import {getHeader} from "../utils/ComponentUtils";
import isEmpty from 'lodash/isEmpty';
import trim from 'lodash/trim';


const DynamicGrid = ({
                       columnDef, frameworkComponents, rowData, context, withHeader, buttons
                    }) => {

  let onFieldSelect = (value, option) => {
    context.selectedField = value
  }

  let onSearch = (value, event) => {
    if(!context.gridApi){
      return
    }
    let gridApi = context.gridApi

    if(isEmpty(trim(value))){
      gridApi.setQuickFilter(null)
    }

    let filterForColumn = gridApi.getFilterInstance(context.selectedField)
    if(!filterForColumn){
      gridApi.setQuickFilter(trim(value))
      return
    }

    let filterModel = {type:"contains", filter: trim(value)}
    filterForColumn.setModel(filterModel)
    context.gridApi.onFilterChanged()
  }

  function getGridHeader(columnDef, rowData, withHeader, buttons){
    if(withHeader){
      return (
        <HeaderBar>
          {getHeader(columnDef, rowData, onSearch, onFieldSelect, buttons)}
        </HeaderBar>
      )
    }else{
      return (<div></div>)
    }

  }

  return (
    <div style=
           {{
             width: '100%',
             height: '100%',
             position: 'relative'
           }}
         className="ag-theme-balham">

      {getGridHeader(columnDef, rowData, withHeader, buttons)}
          <AgGridReact
        columnDefs={columnDef}
        rowData={rowData}
        context={context}
        frameworkComponents={frameworkComponents}
        onGridReady={(gridOptions) => {
          context.gridApi = gridOptions.api
        }}
      />
    </div>
  )
}

DynamicGrid.propTypes = {
  columnDef: PropTypes.array,
  frameworkComponents: PropTypes.object,
  rowData: PropTypes.array,
  context: PropTypes.object,
  onGridReady: PropTypes.func,
  withHeader: PropTypes.bool
}

export default DynamicGrid
